package zhanglinwei.cryptotools.core.wrapper;

import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.SystemEnvironmentOrigin;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import zhanglinwei.cryptotools.core.resolver.CryptoablePropertyResolver;
import zhanglinwei.cryptotools.core.source.CacheCryptoablePropertySource;
import zhanglinwei.cryptotools.core.source.CryptoablePropertySource;

import java.util.Map;

public class CryptoableSystemEnvironmentPropertySourceWrapper extends SystemEnvironmentPropertySource implements CryptoablePropertySource<Map<String, Object>> {

    private final CacheCryptoablePropertySource<Map<String, Object>> cacheCryptoableDelegate;

    public CryptoableSystemEnvironmentPropertySourceWrapper(SystemEnvironmentPropertySource delegate, CryptoablePropertyResolver resolver) {
        super(delegate.getName(), delegate.getSource());
        cacheCryptoableDelegate = new CacheCryptoablePropertySource<>(delegate, resolver);
    }

    @Override
    public Object getProperty(String name) {
        return cacheCryptoableDelegate.getProperty(name);
    }

    @Override
    public PropertySource<Map<String, Object>> getDelegate() {
        return cacheCryptoableDelegate;
    }

    @Override
    public Origin getOrigin(String key) {
        Origin fromSuper = CryptoablePropertySource.super.getOrigin(key);
        if (fromSuper != null) {
            return fromSuper;
        }
        String property = resolvePropertyName(key);
        if (super.containsProperty(property)) {
            return new SystemEnvironmentOrigin(property);
        }
        return null;
    }

    @Override
    public void refresh() {

    }
}
